<template>
  <div class="report-list">
    <n-card>
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>{{ t('menu.reportList') }}</span>
          <n-button size="small" quaternary @click="resetColumnWidths">
            <template #icon>
              <n-icon><Icons name="refresh-outline" /></n-icon>
            </template>
            重置列宽
          </n-button>
        </div>
      </template>

      <div class="search-form">
        <n-form inline :model="searchForm" :show-label="false">
          <n-form-item>
            <n-select
              v-model:value="searchForm.type"
              :placeholder="t('report.type')"
              clearable
              :options="typeOptions"
              style="width: 120px"
            />
          </n-form-item>
          <n-form-item>
            <n-input
              v-model:value="searchForm.reporterName"
              :placeholder="t('report.reporter')"
              clearable
            />
          </n-form-item>
          <n-form-item>
            <n-select
              v-model:value="searchForm.status"
              :placeholder="t('common.status')"
              clearable
              :options="statusOptions"
              style="width: 120px"
            />
          </n-form-item>
          <n-form-item>
            <n-button type="primary" @click="handleSearch">
              {{ t('common.search') }}
            </n-button>
            <n-button @click="handleReset" style="margin-left: 8px">
              {{ t('common.reset') }}
            </n-button>
          </n-form-item>
        </n-form>
      </div>

      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :scroll-x="1600"
        :class="{ 'resizing': isResizing }"
        @update:page="handlePageChange"
      />
    </n-card>

    <n-modal v-model:show="showModal" preset="dialog" title="举报详情" style="width: 70%">
      <div class="report-detail" v-if="currentReport">
        <div class="detail-section">
          <h4>举报信息</h4>
          <div class="detail-item">
            <label>举报类型:</label>
            <n-tag size="small">{{ getTypeText(currentReport.type) }}</n-tag>
          </div>
          <div class="detail-item">
            <label>举报原因:</label>
            <span>{{ currentReport.reason }}</span>
          </div>
          <div class="detail-item">
            <label>详细描述:</label>
            <div class="description">{{ currentReport.description }}</div>
          </div>
          <div class="detail-item">
            <label>举报时间:</label>
            <span>{{ currentReport.createTime }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>举报人信息</h4>
          <div class="detail-item">
            <label>举报人:</label>
            <span>{{ currentReport.reporterName }}</span>
          </div>
          <div class="detail-item">
            <label>举报人ID:</label>
            <span>{{ currentReport.reporterId }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>被举报内容</h4>
          <div class="detail-item">
            <label>内容预览:</label>
            <div class="target-content">
              {{ currentReport.targetContent }}
            </div>
          </div>
          <div class="detail-item">
            <label>目标ID:</label>
            <span>{{ currentReport.targetId }}</span>
          </div>
        </div>

        <div class="detail-section" v-if="currentReport.status !== 'pending'">
          <h4>处理信息</h4>
          <div class="detail-item">
            <label>处理状态:</label>
            <n-tag :type="getStatusType(currentReport.status)" size="small">
              {{ getStatusText(currentReport.status) }}
            </n-tag>
          </div>
          <div class="detail-item" v-if="currentReport.handlerName">
            <label>处理人:</label>
            <span>{{ currentReport.handlerName }}</span>
          </div>
          <div class="detail-item" v-if="currentReport.handleTime">
            <label>处理时间:</label>
            <span>{{ currentReport.handleTime }}</span>
          </div>
          <div class="detail-item" v-if="currentReport.handleResult">
            <label>处理结果:</label>
            <div class="handle-result">{{ currentReport.handleResult }}</div>
          </div>
        </div>

        <div class="report-actions" v-if="currentReport.status === 'pending'">
          <h4>处理操作</h4>
          <n-form :model="handleForm" label-placement="left" label-width="80px">
            <n-form-item label="处理结果:">
              <n-input 
                v-model:value="handleForm.result"
                type="textarea"
                :rows="3"
                placeholder="请输入处理结果说明..."
              />
            </n-form-item>
            <n-form-item>
              <n-space>
                <n-button type="success" @click="handleApprove(currentReport)">
                  通过举报
                </n-button>
                <n-button type="error" @click="handleReject(currentReport)">
                  拒绝举报
                </n-button>
              </n-space>
            </n-form-item>
          </n-form>
        </div>
      </div>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, h } from 'vue'
import { useI18n } from 'vue-i18n'
import { useResizableColumns } from '@/composables/useResizableColumns'
import {
  NCard,
  NButton,
  NIcon,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  NDataTable,
  NTag,
  NModal,
  NSpace,
  useMessage,
  useDialog
} from 'naive-ui'
import { 
  EyeOutline, 
  CheckmarkCircleOutline, 
  CloseCircleOutline 
} from '@/components/Icons'
import Icons from '@/components/Icons.vue'
import { reportApi } from '@/api'

const { t } = useI18n({ useScope: 'global' })
const message = useMessage()
const dialog = useDialog()

const loading = ref(false)
const showModal = ref(false)
const currentReport = ref<any>(null)

const searchForm = reactive({
  type: null,
  reporterName: '',
  status: null
})

const handleForm = reactive({
  result: ''
})

const tableData = ref([])
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50],
  showQuickJumper: true,
  prefix: ({ itemCount }: any) => t('common.total', { count: itemCount })
})

const typeOptions = [
  { label: '评论举报', value: 'comment' },
  { label: '新闻举报', value: 'news' },
  { label: '用户举报', value: 'user' }
]

const statusOptions = computed(() => [
  { label: t('report.status.pending'), value: 'pending' },
  { label: t('report.status.approved'), value: 'approved' },
  { label: t('report.status.rejected'), value: 'rejected' }
])

const getTypeText = (type: string) => {
  const option = typeOptions.find(o => o.value === type)
  return option?.label || type
}

const getStatusType = (status: string) => {
  switch (status) {
    case 'approved':
      return 'success'
    case 'pending':
      return 'warning'
    case 'rejected':
      return 'error'
    default:
      return 'default'
  }
}

const getStatusText = (status: string) => {
  return t(`report.status.${status}`)
}

const getStatusTag = (status: string) => {
  return h(NTag, { 
    type: getStatusType(status),
    size: 'small' 
  }, () => getStatusText(status))
}

const getTypeTag = (type: string) => {
  const colors: any = {
    comment: 'info',
    news: 'warning',
    user: 'error'
  }
  return h(NTag, { 
    type: colors[type] || 'default',
    size: 'small' 
  }, () => getTypeText(type))
}

// 基础列配置
const baseColumns = [
  {
    title: 'ID',
    key: 'id',
    width: 60,
    minWidth: 50,
    maxWidth: 100
  },
  {
    title: t('report.type'),
    key: 'type',
    width: 100,
    minWidth: 80,
    maxWidth: 150,
    render: (row: any) => getTypeTag(row.type)
  },
  {
    title: t('report.targetContent'),
    key: 'targetContent',
    width: 200,
    minWidth: 150,
    maxWidth: 300,
    ellipsis: { tooltip: true }
  },
  {
    title: t('report.reporter'),
    key: 'reporterName',
    width: 120,
    minWidth: 80,
    maxWidth: 200
  },
  {
    title: t('report.reason'),
    key: 'reason',
    width: 80,
    minWidth: 60,
    maxWidth: 150,
    ellipsis: { tooltip: true }
  },
  {
    title: t('common.status'),
    key: 'status',
    width: 80,
    minWidth: 60,
    maxWidth: 120,
    render: (row: any) => getStatusTag(row.status)
  },
  {
    title: t('common.createTime'),
    key: 'createTime',
    width: 160,
    minWidth: 120,
    maxWidth: 200
  },
  {
    title: '处理时间',
    key: 'handleTime',
    width: 160,
    minWidth: 120,
    maxWidth: 200,
    render: (row: any) => row.handleTime || '-'
  },
  {
    title: t('common.operation'),
    key: 'actions',
    width: 240,
    minWidth: 200,
    maxWidth: 300,
    resizable: false, // 操作列不允许调整
    render: (row: any) => {
      const buttons = [
        h(NButton, {
          size: 'small',
          onClick: () => handleView(row)
        }, { default: () => t('common.view'), icon: () => h(NIcon, () => h(EyeOutline)) })
      ]

      if (row.status === 'pending') {
        buttons.push(
          h(NButton, {
            size: 'small',
            type: 'success',
            onClick: () => handleApprove(row),
            style: { marginLeft: '8px' }
          }, { default: () => '通过', icon: () => h(NIcon, () => h(CheckmarkCircleOutline)) }),
          
          h(NButton, {
            size: 'small',
            type: 'error',
            onClick: () => handleReject(row),
            style: { marginLeft: '8px' }
          }, { default: () => '拒绝', icon: () => h(NIcon, () => h(CloseCircleOutline)) })
        )
      }
      
      return h('div', buttons)
    }
  }
]

// 使用可调整列宽的Hook
const { resizableColumns, resetColumnWidths, isResizing } = useResizableColumns({
  columns: baseColumns,
  tableKey: 'report-list',
  defaultWidths: {
    'id': 60,
    'type': 100,
    'targetContent': 200,
    'reporterName': 120,
    'reason': 80,
    'status': 80,
    'createTime': 160,
    'handleTime': 160,
    'actions': 240
  }
})

const columns = computed(() => {
  console.log('🎯 组件中的columns计算:', {
    resizableColumnsLength: resizableColumns.value.length,
    hasRenderHeaders: resizableColumns.value.map(col => ({ key: col.key, hasRender: !!col.renderHeader })),
    firstColumn: resizableColumns.value[0]
  })
  return resizableColumns.value
})

const loadData = async () => {
  try {
    loading.value = true
    
    // 为了测试，先加载模拟数据
    console.log('📡 开始加载数据...')
    
    // 模拟数据以确保表格渲染
    const mockData = [
      {
        id: 1,
        type: 'comment',
        targetContent: '这是一个测试评论内容',
        reporterName: '张三',
        reason: '违规内容',
        status: 'pending',
        createTime: '2024-01-01 10:00:00',
        handleTime: null
      },
      {
        id: 2,
        type: 'news',
        targetContent: '这是一个测试新闻内容',
        reporterName: '李四',
        reason: '垃圾信息',
        status: 'approved',
        createTime: '2024-01-02 11:00:00',
        handleTime: '2024-01-02 15:00:00'
      }
    ]
    
    tableData.value = mockData
    pagination.itemCount = 2
    
    console.log('📊 数据加载完成，表格数据:', tableData.value.length, '条')
    
    // 正常API调用（暂时注释）
    // const response = await reportApi.getList({
    //   page: pagination.page,
    //   pageSize: pagination.pageSize,
    //   ...searchForm
    // })
    // if (response.success) {
    //   tableData.value = response.data.list
    //   pagination.itemCount = response.data.total
    // }
  } catch (error) {
    message.error('加载数据失败')
    console.error('加载数据错误:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  searchForm.type = null
  searchForm.reporterName = ''
  searchForm.status = null
  pagination.page = 1
  loadData()
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadData()
}

const handleView = (row: any) => {
  currentReport.value = row
  handleForm.result = ''
  showModal.value = true
}

const handleApprove = (row: any) => {
  if (!handleForm.result.trim()) {
    message.error('请输入处理结果说明')
    return
  }

  dialog.success({
    title: '确认操作',
    content: `确认通过此举报吗？`,
    positiveText: t('common.confirm'),
    negativeText: t('common.cancel'),
    onPositiveClick: async () => {
      try {
        await reportApi.handle(row.id, handleForm.result)
        message.success('举报处理完成')
        showModal.value = false
        loadData()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleReject = (row: any) => {
  if (!handleForm.result.trim()) {
    message.error('请输入处理结果说明')
    return
  }

  dialog.warning({
    title: '确认操作',
    content: `确认拒绝此举报吗？`,
    positiveText: t('common.confirm'),
    negativeText: t('common.cancel'),
    onPositiveClick: async () => {
      try {
        await reportApi.handle(row.id, handleForm.result)
        message.success('举报已拒绝')
        showModal.value = false
        loadData()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 16px;
}

.report-detail {
  padding: 16px;
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  color: #333;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 8px;
}

.detail-item {
  margin-bottom: 12px;
  display: flex;
  align-items: flex-start;
}

.detail-item label {
  font-weight: bold;
  margin-right: 12px;
  width: 100px;
  flex-shrink: 0;
}

.description,
.target-content,
.handle-result {
  flex: 1;
  background: #f5f5f5;
  padding: 8px 12px;
  border-radius: 4px;
  word-break: break-word;
}

.report-actions {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e0e0e0;
}

.report-actions h4 {
  margin: 0 0 16px 0;
  color: #333;
}
</style>